import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const tenantId = ref('')
    const username = ref('')
    const lastPath = ref('')

    const setToken = (newToken: string) => {
      token.value = newToken
      localStorage.setItem('token', newToken)
    }

    const setTenantId = (newTenantId: string) => {
      tenantId.value = newTenantId
      localStorage.setItem('tenantId', newTenantId)
    }

    const setUsername = (newUsername: string) => {
      username.value = newUsername
      localStorage.setItem('username', newUsername)
    }

    const setLastPath = (path: string) => {
      lastPath.value = path
      localStorage.setItem('lastPath', path)
    }

    const clear = () => {
      token.value = ''
      tenantId.value = ''
      username.value = ''
      localStorage.removeItem('token')
      localStorage.removeItem('tenantId')
      localStorage.removeItem('username')
      localStorage.removeItem('lastPath')
    }

    // 初始化状态
    const initState = () => {
      const storedToken = localStorage.getItem('token')
      const storedTenantId = localStorage.getItem('tenantId')
      const storedUsername = localStorage.getItem('username')
      const storedLastPath = localStorage.getItem('lastPath')

      if (storedToken) token.value = storedToken
      if (storedTenantId) tenantId.value = storedTenantId
      if (storedUsername) username.value = storedUsername
      if (storedLastPath) lastPath.value = storedLastPath
    }

    return {
      token,
      tenantId,
      username,
      lastPath,
      setToken,
      setTenantId,
      setUsername,
      setLastPath,
      clear,
      initState,
    }
  },
  {
    persist: true, // 开启状态持久化
  },
)
